const express = require('express');
const router = express.Router();
const GardenModel = require('../model/garden'); // 确保路径正确指向你的模型文件

/* GET home page. */
router.get('/', function (req, res, next) {
    res.send({
        code: 200,
        msg: "ok"
    });
});

// 查询花朵数量
router.get('/GetFlowerQuantityAndRecordIDs', async (req, res, next) => {
    const uid = req.query.UID;
    console.log('收到的UID:', uid);
    const token = req.headers.authorization.split(' ')[1]; // 去除 "Bearer " 后的 token
    if (!token) {
        return res.status(401).send({
            code: 401,
            msg: '未授权访问，缺少 token'
        });
    }
    if (!uid) {
        return res.status(500).send({
            code: 500,
            msg: '请输入正确的UID'
        });
    }
    try {
        const result = await GardenModel.getFlowerQuantityAndRecordIDs(uid);
        res.status(200).send({
            code: 200,
            msg: "成功获取花朵数量和RecordID数组",
            data: {
                flowerCount: result.flowerCount,
                recordIDs: result.recordIDs
            }
        });
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: `数据查询失败: ${error.message}`
        });
    }
});

// 根据RecordID查询EXP
router.get('/GetFlowerExp', async (req, res, next) => {
    const recordID = req.query.RecordID;
    const token = req.headers.authorization.split(' ')[1]; // 去除 "Bearer " 后的 token
    if (!token) {
        return res.status(401).send({
            code: 401,
            msg: '未授权访问，缺少 token'
        });
    }
    try {
        const exp = await GardenModel.getExpByRecordID(recordID);
        res.status(200).send({
            code: 200,
            msg: "成功获取EXP值",
            data: exp
        });
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: `获取EXP值失败: ${error.message}`
        });
    }
});

// 查询对应花ID
router.get('/GetFlowerID', async (req, res, next) => {
    const recordID = req.query.RecordID;
    const token = req.headers.authorization.split(' ')[1]; // 去除 "Bearer " 后的 token
    if (!token) {
        return res.status(401).send({
            code: 401,
            msg: '未授权访问，缺少 token'
        });
    }
    try {
        const flowerID = await GardenModel.getFlowerIDByRecordID(recordID);
        res.status(200).send({
            code: 200,
            msg: "成功获取FlowerID",
            data: flowerID
        });
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: `获取FlowerID失败: ${error.message}`
        });
    }
});

// 更新用户数据的公用方法
async function updateGardenData(req, res, next, dataType) {
    const { RecordID, newData } = req.body;
    const token = req.headers.authorization.split(' ')[1]; // 去除 "Bearer " 后的 token
    console.log('收到的Token:', token);
    if (!token) {
        return res.status(401).send({
            code: 401,
            msg: '未授权访问，缺少 token'
        });
    }
    try {
        const success = await GardenModel.updateGarden(dataType, RecordID, newData);
        if (success) {
            res.status(200).send({
                code: 200,
                msg: `成功更新 RecordID 为 ${RecordID} 的 ${dataType} 数据为 ${newData}`,
                data: newData 
            });
        } else {
            res.status(404).send({
                code: 404,
                msg: `找不到RecordID为 ${RecordID} 的记录或更新失败`
            });
        }
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: `更新花园数据失败: ${error.message}`
        });
    }
}

// 为用户添加花朵记录
router.post('/AddFlower', async (req, res, next) => {
    try {
        const { UID } = req.body;
        const token = req.headers.authorization.split(' ')[1]; // 去除 "Bearer " 后的 token
        console.log('收到的Token:', token);
        if (!token) {
            return res.status(401).send({
                code: 401,
                msg: '未授权访问，缺少 token'
            });
        }
        const result = await GardenModel.addRandomFlower(UID);
        if (result) {
            res.status(200).send({
                code: 200,
                msg: '添加用户花朵信息成功'
            });
        } else {
            res.status(500).send({
                code: 500,
                msg: `添加用户花朵信息失败: ${error.message}`
            });
        }
    } catch (error) {
        // 捕获并处理可能的异常
        console.error('Error adding flower record:', error.message);
        res.status(500).send({ 
            code: 500,
            msg: `添加用户花朵信息失败: ${error.message}`
        });
    }
});

// 更新花ID
router.post('/UpdateFlowerID', async (req, res, next) => {
    await updateGardenData(req, res, next, 'FlowerID');
});

// 更新花Exp
router.post('/UpdateFlowerExp', async (req, res, next) => {
    await updateGardenData(req, res, next, 'Exp');
});

module.exports = router;
